package com.sunlx.product.utils;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.sunlx.product.dictionary.AlterTableTypeEnum;
import com.sunlx.product.domain.vo.TableDataVo;

import java.util.Arrays;
import java.util.List;

/**
 * sql 生成器   生成数据库修改语句
 *
 * @author Sunluxin
 * @date 2023/1/13 17:33
 */
public class GeneColumnDllSqlUtils {
    public static String TEMPLATE="alter table %s %s (column %s %s  default %s comment '%s' )";
    public static String TEMPLATE_NO_DEFUALT="alter table %s %s (column %s %s  comment '%s' )";

    public static List<String> only_lenght= Arrays.asList("NVARCHAR2","CHAR","");
    public static List<String> precisionAndScale= Arrays.asList("NUMBER","","");
    public static List<String> noLenght= Arrays.asList("DATE","TIMESTAMP","TIMESTAMP(6)","FLOAT");

    public static String geneSqlOralce(TableDataVo tableDataVo, AlterTableTypeEnum alterTableTypeEnum){
        String dataType="";//varchar(2)  ,numric(12,2) ,date 三类
        if(only_lenght.contains(tableDataVo.getDataType())){
            dataType=tableDataVo.getDataType()+"("+tableDataVo.getDataLenght()+")";
        }else if(precisionAndScale.contains(tableDataVo.getDataType())){
            dataType=tableDataVo.getDataType()+"("+tableDataVo.getDataPrecision()+","+tableDataVo.getDataScale()+")";
        }else if(noLenght.contains(tableDataVo.getDataType())){

            dataType=tableDataVo.getDataType() ;
        }else{
            dataType="未经识别的字段类型，请在GeneColumnDLLSqlUtils 中维护"+tableDataVo.getDataType();
        }
        String sql_dll="";
        if(ObjectUtils.isNotEmpty(tableDataVo.getDataDefault())){
            sql_dll=  String.format(TEMPLATE,
                    tableDataVo.getTabelName(),
                    alterTableTypeEnum.getType(),
                    tableDataVo.getColumnName(),
                    dataType,
                    tableDataVo.getDataDefault(),
                    tableDataVo.getComments()
            );
        }else{
            sql_dll=  String.format(TEMPLATE_NO_DEFUALT,
                    tableDataVo.getTabelName(),
                    alterTableTypeEnum.getType(),
                    tableDataVo.getColumnName(),
                    dataType,
                    tableDataVo.getComments()
            );
        }

        if(tableDataVo.getNullable()){
            sql_dll += " null ";
        }else{
            sql_dll+=" not null ";
        }

        return sql_dll;
    }
}
